import express from "express";
import { renderToString } from "react-dom/server";
import path from "path";
import ejs from "ejs";
import fs from "fs";
import { getServerApp } from "../../shared/App";
import { getUserInfo } from "../services/user";
import { NextFunction, Request, Response } from "express";

const router = express.Router();
router.use((req, res, next) => {
  if (req.path === '/manifest.json') {
    res.setHeader('Content-Type', 'application/json');
  } else {
    res.setHeader("Content-Type", "text/html");
  }
  next();
});

// 读取webpack生成的资源文件
const getAssets = () => {
  try {
    const manifestPath = path.join(__dirname, "client/static/asset-manifest.json");
    const manifestContent = fs.readFileSync(manifestPath, "utf-8");
    const manifest = JSON.parse(manifestContent);
    return {
      js: Object.values(manifest).filter((file: any) => file.endsWith(".js")),
      css: Object.values(manifest).filter((file: any) => file.endsWith(".css")),
    };
  } catch (error) {
    console.error("读取asset-manifest.json失败", error);
    return {
      js: [],
      css: [],
    };
  }
};

// 读取模板文件
const getTemplate = () => {
  try {
    const templatePath = path.join(__dirname, "template.ejs");
    const template = fs.readFileSync(templatePath, "utf-8");
    return template || "";
  } catch (err) {
    console.error("读取template.ejs失败", err);
    return "";
  }
};

router.get("*", async (req: Request, res: Response, next: NextFunction) => {
  try {
    // 获取用户信息
    const userInfo = getUserInfo();
    const initialState = { userInfo };
    const template = getTemplate();
    
    if (!template) {
      res.status(404).send("Not Found");
      return;
    }
    
    const html = renderToString(getServerApp('/website' + req.url, initialState));
    
    const htmlStr = await ejs.render(
      template,
      {
        html,
        assets: getAssets(),
        initialState: JSON.stringify(initialState),
      },
      { async: true }
    );
    
    res.send(htmlStr);
  } catch (err) {
    next(err);
  }
});

export default router;
